<template>
  <div v-loading="loading" class="purchase">
    <searchHead :search-data="searchData" @search="handleCurrentChange(1)" @reset="reset" @download="download" />
    <essTable
      ref="table"
      :thead-list="theadList"
      :resize-observer-ele="resizeObserverEle"
      :other-container-box="otherContainerBox"
      :page-num="searchData.pageNum - 1 + 2"
      :total="total"
      :data-list="dataList"
      @search="search"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @selectionChange="selectionChange"
      @operationLog="operationLog"
    >
      <template v-slot:imageUrl="{ scope }">
        <el-image class="mainImg" :src="scope.row.imageUrl || '' | transImgUrl" :preview-src-list="[scope.row.imageUrl || ''] | transImgUrl" />
      </template>
      <template v-slot:channelId="{ scope }">
        <span>{{ processList[scope.row.channelId] }}</span>
      </template>
      <template v-slot:mainStatus="{ scope }">
        <span>{{ scope.row.mainStatus | mainStatus }}</span>
      </template>
      <template v-slot:operationCode="{ scope }">
        <span>{{ scope.row.operationCode | operationCodes }}</span>
      </template>
      <template v-slot:sku="{ scope }">
        <span class="el-button--text el-button--mini" @click="viewDetail(scope.row)">{{ scope.row.sku }}</span>
      </template>
      <div slot="right" name="right">
        <el-button :disabled="!multipleSelection.length" size="mini" type="primary" round @click="onsubmit">提交</el-button>
        <el-button :disabled="!multipleSelection.length" size="mini" type="primary" round @click="withDraw">撤回</el-button>
        <el-button :disabled="!multipleSelection.length" size="mini" type="primary" round @click="handleCancel">作废</el-button>
      </div>
    </essTable>
    <operation-log ref="operationLogRef" :table-data="logData" :log-list="commodityMaintainLog">
      <template v-slot:createdTime="{ scope }">
        {{ transDate(scope.row.createdTime) }}
      </template>
    </operation-log>
    <submit-approval-dialog ref="submitApprovalRef" :dialog-loading="dialogLoading" @onsubmit="submitReview" />
  </div>
</template>

<script>
import searchHead from '@/views/coi/commodityM/components/searchHead2.vue'
import essTable from '@/components/eTable/eTable.vue'
import operationLog from '@/views/coi/components/operationLog.vue'
import submitApprovalDialog from '@/views/coi/commodityM/components/submitApprovalDialog.vue'
import { commodityMaintainList } from '@/views/coi/commonJs/tableHeadList'
import { maintainList, commoditylibraryExport, operationLogByProcessId, cancellation, revocation, submitApproval } from '@/api/coi/onlineTaskAPI/sku'
import moment from 'moment'
import eventBus from '@/utils/eventBus'
import { commodityTypes, operationCodes } from '@/views/coi/commonJs/dictionary'
import { commodityMaintainLog } from '@/views/coi/commonJs/operationLogList'
import { authentication, stringToArray } from '@/utils/processingData.js'

export default {
  name: 'CommodityMaintain',
  components: {
    searchHead,
    essTable,
    operationLog,
    submitApprovalDialog
  },
  filters: {
    mainStatus(v) {
      for (let i = 0; i < commodityTypes.length; i++) {
        const el = commodityTypes[i]
        if (el.value === v) {
          return el.label
        }
      }
    },
    operationCodes(v) {
      for (let i = 0; i < operationCodes.length; i++) {
        const el = operationCodes[i]
        if (el.value === v) {
          return el.label
        }
      }
    },
    transImgUrl(url) {
      return authentication(url)
    }
  },
  data() {
    return {
      resizeObserverEle: ['.app-main', '.app-container'],
      otherContainerBox: ['.app-container', '.checkComponent'],
      searchData: {
        pageNum: 0,
        pageSize: 10
      },
      theadList: commodityMaintainList,
      total: 0,
      dataList: [],
      loading: false,
      routerName: this.$route.name,
      logData: [], // 操作日志
      commodityMaintainLog,
      dialogLoading: false,
      dialogVisible: false, // 日志
      multipleSelection: [],
      processList: {
        0: '全渠道',
        12: '沃尔玛到家',
        '07': '京东到家',
        '06': '京东沃选'
      }
    }
  },
  activated() {
    this.handleCurrentChange(1)
  },
  mounted() {
    this.search()
  },
  methods: {
    // 点击检索按钮执行
    async search() {
      const _this = this
      this.$refs.table.clearSelection()
      try {
        this.loading = true
        const { result } = await this.query(this.handleData())
        if (result) {
          this.total = result.total
          this.dataList = result.data
          this.dataList.forEach((item) => {
            item.createdTime = _this.transDate(item.createdTime)
            item.updatedTime = _this.transDate(item.updatedTime)
          })
        }
      } finally {
        this.loading = false
      }
    },
    transDate(v) {
      if (v === null) {
        return ''
      }
      return moment(v).format('YYYY-MM-DD HH:mm:ss')
    },
    async query(searchData) {
      return await maintainList(searchData)
    },
    handleData() {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      searchData.skuList = stringToArray(searchData.skuList, /[\n\r]/) // upc(不含检验码)
      if (searchData.time) {
        searchData.startCreateTime = moment(this.searchData.time[0]).format('YYYY-MM-DD HH:mm:ss')
        searchData.endCreateTime = moment(this.searchData.time[1]).format('YYYY-MM-DD HH:mm:ss')
        delete searchData.time
      }
      for (const key in searchData) {
        if (typeof searchData[key] !== 'number' && !searchData[key].length) {
          delete searchData[key]
        }
      }
      return searchData
    },
    // 重置检索条件
    reset() {
      this.searchData = {
        pageSize: 10,
        pageNum: 0
      }
      this.search()
    },
    // 导出
    async download() {
      const date = moment(new Date()).format('YYYY-MM-DD')
      commoditylibraryExport(this.searchData, `线上商品库 ${date}`)
    },
    // 分页器
    handleCurrentChange(val) {
      this.searchData.pageNum = val - 1
      this.search()
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val
      this.handleCurrentChange(1)
    },
    selectionChange(val) {
      this.multipleSelection = val
    },
    // 操作日志
    async operationLog({ row }) {
      const { result } = await operationLogByProcessId(row.id)
      if (Array.isArray(result) && result.length) {
        // this.dialogVisible = true
        this.$refs.operationLogRef.dialogVisible = true
        this.logData = result
      } else {
        this.$message({
          type: 'warning',
          message: '未查询到该商品线上建品的操作日志'
        })
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    viewDetail(row) {
      eventBus.$emit('setTagName', row.skuName)
      let type = 'edit'
      if ([9012, 9020, 9030, 9032, 9040, 9050, 9060, 9070, 90750, 9076].indexOf(row.mainStatus) !== -1) {
        type = 'detail'
      }
      this.$router.push({
        path: `/commodityM/commodityEdit/${row.id}/${type}/${this.$route.name}/${row.channelId}`,
        query: { tab: '' }
      })
    },
    // 提交
    onsubmit() {
      this.$refs.submitApprovalRef.dialogVisible = true
    },
    // 提交审核
    submitReview(remark) {
      this.dialogLoading = true
      const ids = []
      this.multipleSelection.forEach((item) => {
        ids.push(item.id)
      })
      const param = {
        idList: ids,
        submitTrialRemark: remark
      }
      submitApproval(param).then((res) => {
        if (res) {
          this.dialogLoading = false
          this.$refs.submitApprovalRef.dialogVisible = false
          this.$message({
            type: 'success',
            message: '提交成功!'
          })
          this.handleCurrentChange(1)
        }
      })
    },
    // 撤回
    withDraw() {
      this.$confirm('此操作将撤回选中数据的提交, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = []
        this.multipleSelection.forEach((item) => {
          param.push(item.id)
        })
        revocation(param).then((res) => {
          if (res.result) {
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.handleCurrentChange(1)
          }
        })
      })
    },
    // 作废
    handleCancel() {
      this.$confirm('此操作将废除选中数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const param = []
        this.multipleSelection.forEach((item) => {
          param.push(item.id)
        })
        cancellation(param).then((res) => {
          if (res.result) {
            this.$message({
              type: 'success',
              message: '废除成功!'
            })
            this.handleCurrentChange(1)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.purchase {
  height: calc(100%);
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  overflow-y: auto;
  max-height: 75vh;
}
/deep/ .el-dialog__footer {
  padding: 10px 20px;
}
.details {
  /deep/ .el-dialog__body {
    padding: 0;
    padding-bottom: 20px;
  }
}
.remark {
  margin: 8px 0;
  display: flex;
  justify-content: flex-start;
  .remarkTitle {
    width: 70px;
    line-height: 20px;
  }
  .remarkList {
    flex: 1;
    line-height: 20px;
  }
}
.mainImg {
  max-width: 50px;
  max-height: 50px;
}
</style>
